package com.siyoumi.app.sys.wx_open;

import com.siyoumi.app.sys.service.wxapi.WxApiOpen;
import com.siyoumi.app.sys.vo.WxOpenOauthVo;
import com.siyoumi.component.XApp;
import com.siyoumi.component.http.XHttpContext;
import com.siyoumi.config.SysConfig;
import com.siyoumi.controller.ApiController;
import com.siyoumi.entity.SysAccsuperConfig;
import com.siyoumi.util.XReturn;
import com.siyoumi.util.XStr;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

//放开平台授权
@Slf4j
@RestController
@RequestMapping("/wx_open/server/oauth")
public class WxOpenOauth
        extends ApiController {
    @GetMapping("index.html")
    public String indexHtml() {
        return XApp.getFileContent("view/wx_open/index.html");
        //return XApp.getFileContent("view/sys_log/error.html");
    }

    //@GetMapping("callback_msg.html")
    //public String callbackMsgHtml() {
    //    return XApp.getFileContent("view/wx_open/callback_msg.html");
    //}

    @GetMapping()
    public XReturn index(WxOpenOauthVo vo) {
        XHttpContext.setX("open");
        SysAccsuperConfig entityConfig = XHttpContext.getXConfig();
        WxApiOpen api = WxApiOpen.getIns(entityConfig);
        XReturn r = api.authCode();
        if (r.err()) {
            return r;
        }

        String authCode = r.getData("pre_auth_code");
        String root = SysConfig.getIns().getAppRoot();

        String callbackUrl = XStr.format("{0}wx_open/server/oauth_callback?wxapp={1}&master_xid={2}"
                , root
                , vo.getWxapp().toString()
                , entityConfig.getAconfig_id()
        );
        log.debug("callback_url: {}", callbackUrl);

        Integer authType = 1;
        if (vo.getWxapp() == 1) {
            authType = 2;
        }

        Map<String, String> mapQuery = new HashMap<>();
        mapQuery.put("component_appid", entityConfig.getAconfig_app_id());
        mapQuery.put("pre_auth_code", authCode);
        mapQuery.put("redirect_uri", callbackUrl);
        mapQuery.put("auth_type", authType.toString()); //1：公众号；2：小程序；3：公众号与小程序；

        String query = XStr.queryFromMap(mapQuery, null, true);

        String redirectUrl = "https://mp.weixin.qq.com/cgi-bin/componentloginpage?" + query;
        log.debug("url: {}", redirectUrl);

        getR().setData("url", redirectUrl); //需要页面

        return getR();
    }
}
